import React, { useState } from 'react'; // 导入React和useState
import { Table, Button, Modal, Form, Input, Space, message, Popconfirm, Card, Tag } from 'antd'; // 导入Ant Design组件
import { PlusOutlined, EditOutlined, DeleteOutlined, LinkOutlined, CheckCircleTwoTone, CloseCircleTwoTone } from '@ant-design/icons'; // 导入图标

// 初始数据源数据
const initialDataSources = [
  { id: 1, name: '主数据库', type: 'MySQL', host: '127.0.0.1', port: '3306', status: 'connected', remark: '生产环境' },
  { id: 2, name: 'BI数据仓库', type: 'PostgreSQL', host: '192.168.1.10', port: '5432', status: 'disconnected', remark: '分析用' }
];

const DataSourceManagement = () => {
  // 数据源列表
  const [dataSources, setDataSources] = useState(initialDataSources);
  // 控制模态框显示
  const [modalVisible, setModalVisible] = useState(false);
  // 当前编辑数据源
  const [editing, setEditing] = useState(null);
  // 表单实例
  const [form] = Form.useForm();

  // 打开新增数据源模态框
  const handleAdd = () => {
    setEditing(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 打开编辑数据源模态框
  const handleEdit = (record) => {
    setEditing(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 删除数据源
  const handleDelete = (id) => {
    setDataSources(dataSources.filter(item => item.id !== id));
    message.success('删除成功');
  };

  // 测试连接
  const handleTest = (record) => {
    // 模拟测试连接
    message.loading('正在测试连接...');
    setTimeout(() => {
      if (record.host === '127.0.0.1') {
        setDataSources(dataSources.map(item => item.id === record.id ? { ...item, status: 'connected' } : item));
        message.success('连接成功');
      } else {
        setDataSources(dataSources.map(item => item.id === record.id ? { ...item, status: 'disconnected' } : item));
        message.error('连接失败');
      }
    }, 1000);
  };

  // 提交表单
  const handleOk = () => {
    form.validateFields().then(values => {
      if (editing) {
        // 编辑数据源
        setDataSources(dataSources.map(item => item.id === editing.id ? { ...item, ...values } : item));
        message.success('编辑成功');
      } else {
        // 新增数据源
        const newItem = { id: Date.now(), ...values, status: 'disconnected' };
        setDataSources([...dataSources, newItem]);
        message.success('新增成功');
      }
      setModalVisible(false);
      form.resetFields();
    });
  };

  // 数据源表格列
  const columns = [
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '类型', dataIndex: 'type', key: 'type' },
    { title: '主机', dataIndex: 'host', key: 'host' },
    { title: '端口', dataIndex: 'port', key: 'port' },
    { title: '状态', dataIndex: 'status', key: 'status', render: (text) => text === 'connected' ? <Tag icon={<CheckCircleTwoTone twoToneColor="#52c41a" />} color="success">已连接</Tag> : <Tag icon={<CloseCircleTwoTone twoToneColor="#f5222d" />} color="error">未连接</Tag> },
    { title: '备注', dataIndex: 'remark', key: 'remark' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button icon={<LinkOutlined />} size="small" onClick={() => handleTest(record)}>测试连接</Button>
          <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定删除该数据源吗？" onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
            <Button icon={<DeleteOutlined />} size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <Card title="数据源管理" bordered={false}> {/* 外层卡片 */}
      <Button type="primary" icon={<PlusOutlined />} style={{ marginBottom: 16 }} onClick={handleAdd}>新增数据源</Button>
      <Table columns={columns} dataSource={dataSources} rowKey="id" pagination={false} />
      <Modal
        title={editing ? '编辑数据源' : '新增数据源'}
        open={modalVisible}
        onOk={handleOk}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="名称" rules={[{ required: true, message: '请输入名称' }]}> 
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="type" label="类型" rules={[{ required: true, message: '请输入类型，如MySQL/PostgreSQL' }]}> 
            <Input placeholder="请输入类型，如MySQL/PostgreSQL" />
          </Form.Item>
          <Form.Item name="host" label="主机" rules={[{ required: true, message: '请输入主机地址' }]}> 
            <Input placeholder="请输入主机地址" />
          </Form.Item>
          <Form.Item name="port" label="端口" rules={[{ required: true, message: '请输入端口号' }]}> 
            <Input placeholder="请输入端口号" />
          </Form.Item>
          <Form.Item name="remark" label="备注"> 
            <Input placeholder="备注（可选）" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default DataSourceManagement; // 导出数据源管理组件 